import datetime

import coin.proto.coin_order_enums_pb2 as coin_order_enums
import coin.proto.coin_market_enums_pb2 as coin_market_enums
from coin.proto.coin_order_gateway_pb2 import OrderGatewayLog, OrderEvent
from coin.proto.coin_strategy_pb2 import StrategyLog


def _adjust_bithumb_fill(strat_name, ts, order_event):
  assert order_event.type == OrderEvent.ORDER_FILLED, order_event.type
  dt = datetime.datetime.utcfromtimestamp(ts / 10**9)
  if order_event.order_side == coin_order_enums.BUY_ORDER:
    if dt > datetime.datetime(2019, 12, 16, 7):
      if dt < datetime.datetime(2019, 12, 17, 7) or \
         (dt < datetime.datetime(2019, 12, 18) and
          'pair_bithumb' in strat_name):
        assert order_event.HasField('order_qty')
        assert order_event.HasField('fill_qty')
        assert order_event.HasField('fill_price')
        fee_rate = 0.0003
        order_qty = \
          order_event.order_qty / (1 + order_event.fill_price * fee_rate)
        fill_qty = \
          order_event.fill_qty / (1 + order_event.fill_price * fee_rate)
        order_event.order_qty = order_qty
        order_event.fill_qty = fill_qty


def adjust_strat_log(strat_name, ts, pb):
  assert isinstance(pb, StrategyLog)
  if pb.type == StrategyLog.OG_LOG and \
     pb.og_log.type == OrderGatewayLog.ORDER_EVENT:
    order_event = pb.og_log.event
    if order_event.type == OrderEvent.ORDER_FILLED and \
       order_event.exchange_type == coin_market_enums.Bithumb:
      _adjust_bithumb_fill(strat_name, ts, order_event)
